$(document).ready(function(){
	var allLog = "";
	var taskName = $("#shell-task-name").html();
	var param = {
		taskName:taskName
	};
	
	function loadTaskList() {
		new HttpUtils().post("com.lvtu.dashboard.ssh.getTaskList", param, function(data){
			var respData = data.data;
			if(!respData) {
				return;
			}
			var waitShellList = respData.waitShellList;
			var execIdList = respData.execIdList;
			if(waitShellList) {
				renderShellHold(waitShellList);
			}
			if(execIdList) {
				renderShellHistory(execIdList);
			}
		});
	}
	loadTaskList();
	
	setInterval(function() {
		loadTaskList();
	},60000);
	
	function renderShellHistory(execIdList) {
		$("#shell-history").empty();
		var html = '<a href="#" class="list-group-item active" onclick="return false;">历史任务</a>'
		$.each(execIdList, function (index, execId) {
			if(!execId) {
				return;
			}
			html = html + '<a class="list-group-item" id="history-exec-id-' + execId + '"># '+ execId +'</a>'
		});
		$("#shell-history").append(html);
		$.each(execIdList, function (index, execId) {
			if(!execId) {
				return;
			}
			$("#history-exec-id-" + execId).click(function(){
				var execIdObj = $("#exec-id");
				execIdObj.empty();
				execIdObj.append(execId);
				$("#exec-finish-flag").empty();
				$("#log-last-line").empty();
				$("#shell-console").empty();
				allLog = "";
				return false;
			});
		});
	}
	
	function renderShellHold(waitShellList) {
		$("#shell-hold").empty();
		var html = '<a href="#" class="list-group-item active" onclick="return false;">排队中的任务</a>';
		$.each(waitShellList, function (index, shellName) {
			if(!shellName) {
				return;
			}
			html = html + '<a class="list-group-item"># '+ shellName +'</a>'
		});
		$("#shell-hold").append(html);
	}
	
	setInterval(function () {
		var execId = $("#exec-id").html();
		var execFinishFlag = $("#exec-finish-flag").html();
		if(!execId) {
			return;
		}
		if(execFinishFlag == 'N') {
			return;
		}
		
		var logLastLine = $("#log-last-line").html();
		
		var param = {
			execId:execId,
			lastLine:logLastLine
		};
		new HttpUtils().post("com.lvtu.dashboard.ssh.getLog", param, function(data){
			var execFinishFlag2 = $("#exec-finish-flag").html();
			if(execFinishFlag2 == 'N') {
				return;
			}
			var respData = data.data;
			if(!respData) {
				return;
			}
			$("#exec-finish-flag").empty();
			var active = respData.active;
			if(active == true) {
				$("#exec-finish-flag").append("Y");
			} else {
				$("#exec-finish-flag").append("N");
			}
			$("#log-last-line").empty();
			$("#log-last-line").append(respData.lastLine);
			var logList = respData.logList;
			$.each(logList, function (index, log) {
				allLog = allLog + log;
			});
			var shellConsole = $("#shell-console");
			shellConsole.empty();
			shellConsole.append(allLog);
		});
	},1000);
});